<template>
  <div class="menu-management">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <!-- <h1>菜单管理</h1> -->
      <el-button type="primary" @click="handleAdd"> <Plus /> 新增菜单 </el-button>
    </div>

    <!-- 菜单树和角色分配区域 -->
    <el-row :gutter="20">
      <!-- 菜单树 -->
      <el-col :span="14">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>菜单树形结构</span>
              <el-button type="primary" size="small" @click="refreshMenuTree"> 刷新 </el-button>
            </div>
          </template>

          <el-tree
            :data="menuTree"
            :props="treeProps"
            :expand-on-click-node="false"
            :default-expand-all="true"
            node-key="id"
            ref="menuTreeRef"
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <div class="tree-node-content">
                <span>{{ data.name }}</span>
                <div class="node-operations">
                  <el-button size="mini" @click.stop="handleEdit(data)"> 编辑 </el-button>

                  <el-button size="mini" type="success" @click.stop="handleAddChild(data)">
                    新增子菜单
                  </el-button>
                  <el-button size="mini" type="danger" @click.stop="handleDelete(data.id)">
                    删除
                  </el-button>
                </div>
              </div>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 角色菜单分配 -->
      <el-col :span="10">
        <el-card>
          <template #header>
            <span>角色菜单分配</span>
          </template>

          <el-form>
            <el-form-item label="选择角色">
              <el-select
                v-model="selectedRoleId"
                placeholder="请选择角色"
                @change="handleRoleChange"
              >
                <el-option
                  v-for="role in roles"
                  :key="role.id"
                  :label="role.name"
                  :value="role.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="角色拥有的菜单">
              <el-tree
                :data="menuTree"
                :props="treeProps"
                :checked-keys="checkedMenuIds"
                :expand-on-click-node="false"
                :default-expand-all="false"
                node-key="id"
                show-checkbox
                ref="roleMenuTreeRef"
                @check="handleMenuCheck"
              ></el-tree>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleAssignMenus" :disabled="!selectedRoleId">
                确认分配
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/编辑菜单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑菜单' : isChild ? '新增子菜单' : '新增菜单'"
      width="500px"
    >
      <el-form ref="menuFormRef" :model="menuForm" :rules="formRules" label-width="100px">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="menuForm.name" placeholder="请输入菜单名称" maxlength="50"></el-input>
        </el-form-item>

        <el-form-item label="路由路径" prop="path">
          <el-input v-model="menuForm.path" placeholder="请输入路由路径"></el-input>
        </el-form-item>

        <el-form-item label="图标" prop="icon">
          <el-input v-model="menuForm.icon" placeholder="请输入图标类名（可选）"></el-input>
          <div class="form-hint">提示：使用Element Plus图标，如"el-icon-menu"</div>
        </el-form-item>

        <el-form-item label="父菜单" prop="parentId">
          <el-select v-model="menuForm.parentId" placeholder="请选择父菜单（可选）">
            <el-option value="" label="无（根菜单）"></el-option>
            <el-option
              v-for="menu in allMenus"
              :key="menu.id"
              :label="getMenuFullPath(menu)"
              :value="menu.id"
              :disabled="isEdit && menu.id === currentMenuId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排序号" prop="sortOrder">
          <el-input
            v-model.number="menuForm.sortOrder"
            placeholder="数字越小越靠前"
            type="number"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit"> 确认 </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { menuApi, roleApi } from '@/api'

// 菜单树数据
const menuTree = ref([])
// 所有菜单列表（用于下拉选择）
const allMenus = ref([])
// 角色列表
const roles = ref([])

// 树形配置
const treeProps = {
  children: 'children',
  label: 'name',
}

// 对话框状态
const dialogVisible = ref(false)
const isEdit = ref(false)
const isChild = ref(false)
const currentMenuId = ref('')

// 表单数据
const menuForm = reactive({
  name: '',
  path: '',
  icon: '',
  parentId: '',
  sortOrder: 0,
})

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { max: 50, message: '菜单名称不能超过50个字符', trigger: 'blur' },
  ],
  path: [{ required: true, message: '请输入路由路径', trigger: 'blur' }],
  sortOrder: [
    { required: true, message: '请输入排序号', trigger: 'blur' },
    { type: 'number', message: '请输入有效的数字', trigger: 'blur' },
  ],
})

// 角色菜单分配相关
const selectedRoleId = ref('')
const checkedMenuIds = ref([])
const tempCheckedMenuIds = ref([])

// 引用
const menuTreeRef = ref(null)
const roleMenuTreeRef = ref(null)
const menuFormRef = ref(null)

// 页面加载时初始化数据
onMounted(async () => {
  await Promise.all([fetchMenuTree(), fetchAllMenus(), fetchRoles()])
})

// 获取菜单树
const fetchMenuTree = async () => {
  try {
    const res = await menuApi.getMenuTree()
    menuTree.value = res || []
  } catch (err) {
    ElMessage.error('获取菜单树失败：' + (err.response?.data?.message || err.message))
  }
}

// 获取所有菜单
const fetchAllMenus = async () => {
  try {
    const res = await menuApi.getAllMenus()
    allMenus.value = res || []
  } catch (err) {
    ElMessage.error('获取菜单列表失败：' + (err.response?.data?.message || err.message))
  }
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const res = await roleApi.getAllRoles()
    roles.value = res || []
  } catch (err) {
    ElMessage.error('获取角色列表失败：' + (err.response?.data?.message || err.message))
  }
}

// 刷新菜单树
const refreshMenuTree = async () => {
  await Promise.all([fetchMenuTree(), fetchAllMenus()])
  ElMessage.success('刷新成功')
}

// 处理节点点击
const handleNodeClick = (data) => {
  console.log('点击节点:', data)
}

// 新增菜单
const handleAdd = () => {
  resetForm()
  isEdit.value = false
  isChild.value = false
  dialogVisible.value = true
}

// 新增子菜单
const handleAddChild = (data) => {
  resetForm()
  isEdit.value = false
  isChild.value = true
  menuForm.parentId = data.id
  dialogVisible.value = true
}

// 编辑菜单
const handleEdit = async (data) => {
  try {
    const res = await menuApi.getMenuById(data.id)
    const menu = res

    menuForm.name = menu.name
    menuForm.path = menu.path
    menuForm.icon = menu.icon
    menuForm.parentId = menu.parentId || ''
    menuForm.sortOrder = menu.sortOrder

    isEdit.value = true
    isChild.value = false
    currentMenuId.value = data.id
    dialogVisible.value = true
  } catch (err) {
    ElMessage.error('获取菜单详情失败：' + (err.response?.data?.message || err.message))
  }
}

// 删除菜单
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该菜单吗？如果有子菜单将无法删除。', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await menuApi.deleteMenu(id)
    ElMessage.success('菜单删除成功')
    await refreshMenuTree()
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('删除失败：' + (err.response?.data?.message || err.message))
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await menuFormRef.value.validate()
    // 处理 parentId：空字符串转为 null
    const submitData = {
      ...menuForm,
      parentId: menuForm.parentId === '' ? null : menuForm.parentId,
    }

    if (isEdit.value) {
      // 编辑菜单
      await menuApi.updateMenu(currentMenuId.value, submitData)
      ElMessage.success('菜单更新成功')
    } else {
      // 新增菜单
      await menuApi.createMenu(submitData)
      ElMessage.success('菜单创建成功')
    }

    dialogVisible.value = false
    await refreshMenuTree()
  } catch (err) {
    if (err.name !== 'ValidationError') {
      ElMessage.error('操作失败：' + (err.response?.data?.message || err.message))
    }
  }
}

// 角色变更时获取其拥有的菜单
const handleRoleChange = async (roleId) => {
  if (!roleId) {
    checkedMenuIds.value = []
    tempCheckedMenuIds.value = []
    return
  }

  try {
    const res = await menuApi.getMenusByRole(roleId)
    const menus = res || []
    checkedMenuIds.value = menus.map((menu) => menu.id)
    tempCheckedMenuIds.value = [...checkedMenuIds.value]
  } catch (err) {
    ElMessage.error('获取角色菜单失败：' + (err.response?.data?.message || err.message))
  }
}

// 处理菜单勾选
const handleMenuCheck = (checkedKeys, checkedNodes) => {
  console.log('菜单勾选事件:', {
    checkedKeys,
    checkedNodes,
    checkedKeysType: typeof checkedKeys,
    isArray: Array.isArray(checkedKeys),
  })

  // 确保checkedKeys是数组且包含有效的GUID
  let validKeys = []
  if (Array.isArray(checkedKeys)) {
    validKeys = checkedKeys.filter((key) => {
      // 检查是否是有效的GUID格式
      const guidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
      return typeof key === 'string' && guidRegex.test(key)
    })
  }

  console.log('过滤后的有效菜单ID:', validKeys)
  tempCheckedMenuIds.value = validKeys
}

// 分配菜单给角色
const handleAssignMenus = async () => {
  if (!selectedRoleId.value) return

  console.log('开始分配菜单:', {
    roleId: selectedRoleId.value,
    menuIds: tempCheckedMenuIds.value,
  })

  try {
    const result = await menuApi.assignMenusToRole(selectedRoleId.value, tempCheckedMenuIds.value)
    console.log('菜单分配成功:', result)
    checkedMenuIds.value = [...tempCheckedMenuIds.value]
    ElMessage.success('菜单分配成功')
  } catch (err) {
    console.error('菜单分配失败:', err)
    console.error('错误详情:', {
      status: err.response?.status,
      statusText: err.response?.statusText,
      data: err.response?.data,
      message: err.message,
    })

    let errorMessage = '菜单分配失败'
    if (err.response?.data?.message) {
      errorMessage += '：' + err.response.data.message
    } else if (err.message) {
      errorMessage += '：' + err.message
    }

    ElMessage.error(errorMessage)
  }
}

// 重置表单
const resetForm = () => {
  menuForm.name = ''
  menuForm.path = ''
  menuForm.icon = ''
  menuForm.parentId = ''
  menuForm.sortOrder = 0

  if (menuFormRef.value) {
    menuFormRef.value.resetFields()
  }
}

// 获取菜单完整路径（用于下拉显示）
const getMenuFullPath = (menu) => {
  if (!menu.parentId) return menu.name

  const parentMenu = allMenus.value.find((m) => m.id === menu.parentId)
  return parentMenu ? `${getMenuFullPath(parentMenu)} / ${menu.name}` : menu.name
}
</script>

<style scoped>
.menu-management {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tree-node-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.node-operations {
  display: none;
  margin-left: 10px;
}

.tree-node-content:hover .node-operations {
  display: flex;
  gap: 5px;
}

.form-hint {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

.el-select {
  width: 100%;
}
</style>
